package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.UUID;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

import myz.date.gui.CalendarPad;
import myz.date.gui.NumberLenghtLimitedDmt;

import org.apache.commons.io.FilenameUtils;

import db.domain.SystemPictur;
import db.domain.SystemPictur;
import db.sqldao.SystemPicturSqlDao;

/**
 * 系统图片组信息界面
 * 
 * @author 冀鲁
 * @date 2011-06-28
 * @version 1.0.0.0
 * 
 */
@SuppressWarnings("serial")
public class SystemPicturManager extends JDialog implements MouseListener,
		ActionListener {
	public SystemPictur SystemPictur;
	private JPanel jp;
	private JLabel lblNo;// 系统图片编号
	private JTextField txtNo;

	private int PicturNum = 10;// 系统图片的数量
	private JLabel lblPicture[] = new JLabel[PicturNum];// 个人照片
	private JButton btnUpload[] = new JButton[PicturNum];// 上传照片

	private JButton btnManager;// 设置
	private JButton btnBack;// 返回

	public SystemPicturManager(SystemPictur systemPictur) {
		int x = 600, y = 600;// 窗口大小
		int x0 = 15, y0 = 55, w0 = 90, h0 = 120;// 图片位置
		int hh = 10;// 按钮与图片的间距
		int dx = 20, dy = 100;// 图片间距
		int tx = 0, ty = 30;// 标签的位置
		int tw = 100, th = 20;// 标签宽的和长度
		SystemPictur = systemPictur;
		this.setTitle("系统皮肤设置界面");
		this.setLayout(null);
		jp = new JPanel(null);// 使用坐标布局

		TitledBorder tb = new TitledBorder("系统图片信息");// 标题
		tb.setTitleColor(Color.red);// 标题颜色
		// 标题字体
		tb.setTitleFont(new Font("黑体", Font.BOLD, 20));
		// 边框颜色和宽度
		tb.setBorder(new LineBorder(Color.blue, 2, false));// false直角true 圆角
		jp.setBorder(tb);
		jp.setBounds(10, 5, x - 30, y - 50);
		this.add(jp);
		// 添加一些组件，添加到jp上

		// 第一行
		lblNo = new JLabel("系统图片组号：");
		lblNo.setHorizontalAlignment(JLabel.RIGHT);// 对齐方式
		// lblNo.setBorder(new LineBorder(Color.red, 1, false));
		lblNo.setBounds(tx, ty, tw, th);
		jp.add(lblNo);
		txtNo = new JTextField();
		txtNo.setBounds(tx + tw + 10, ty, 20, th);
		txtNo.setBorder(new LineBorder(Color.black, 1, false));
		// 只能输入数字，最多五位数
		txtNo.setDocument(new NumberLenghtLimitedDmt(5));
		jp.add(txtNo);

		// 第七行
		btnManager = new JButton("设置");
		btnManager.setBounds(200, y - 100, 80, 30);
		btnManager.addActionListener(this);
		jp.add(btnManager);

		btnBack = new JButton("返回");
		btnBack.setBounds(btnManager.getX() + btnManager.getWidth() + 50,
				btnManager.getY(), btnManager.getWidth(), btnManager
						.getHeight());
		btnBack.addActionListener(this);
		jp.add(btnBack);

		/* 系统图片 */
		for (int i = 0; i < PicturNum; i++) {
			int j;// 换行
			if (i / 5 == 1) {
				j = 1;
			} else {
				j = 0;
			}
			lblPicture[i] = new JLabel(
					"<html>		未<br>		上<br>		传<br>		皮<br>		肤<br></html>");
			lblPicture[i].setBorder(new LineBorder(Color.blue, 5, true));
			lblPicture[i].setBounds(x0 + i * (w0 + dx) - j * 5 * (w0 + dx), y0
					+ j * (h0 + dy), w0, h0);
			jp.add(lblPicture[i]);

			btnUpload[i] = new JButton("上传照片");
			btnUpload[i].setBounds(lblPicture[i].getX(), lblPicture[i].getY()
					+ lblPicture[i].getHeight() + hh, 90, 30);
			btnUpload[i].addActionListener(this);
			jp.add(btnUpload[i]);

		}

		this.setModal(true);// 窗口独占模式（JDialog独有）
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		// 匿名内部类
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent arg0) {
				closeWindow();
			}
		});

		this.setSize(x, y);
		this.setResizable(false);
		displaysystemPictur(systemPictur);

		this.setVisible(true);
	}

	protected void closeWindow() {
		// 关闭窗口
		this.dispose();// 释放本窗口资源
	}

	public void mouseClicked(MouseEvent e) {
		if (e.getButton() == MouseEvent.BUTTON1/* 左键 */) {
			// 获取鼠标的位置
			double x = e.getLocationOnScreen().getX();
			double y = e.getLocationOnScreen().getY();
			CalendarPad cp = new CalendarPad(2010, 4, 27, x, y);
			// txtBirthday.setText(cp.toString());
		}
	}

	public void mouseEntered(MouseEvent e) {

	}

	public void mouseExited(MouseEvent e) {

	}

	public void mousePressed(MouseEvent e) {

	}

	public void mouseReleased(MouseEvent e) {

	}

	public void actionPerformed(ActionEvent e) {
		for (int i = 0; i < PicturNum; i++) {
			if (e.getSource() == btnUpload[i]) {
				Savepoint(i, lblPicture[i]);
			}
		}
		if (e.getSource() == btnManager) { // 设置
			SetPictur();
		} else if (e.getSource() == btnBack) { // 返回
			this.dispose();// 释放本窗口资源
		}
	}

	/**
	 * 设置成背景
	 */

	private void SetPictur() {
		SystemPictur systemPictur = new SystemPictur();
		systemPictur = SystemPictur;
		systemPictur.setNo(11111);
		SystemPicturSqlDao sDao = new SystemPicturSqlDao();
		sDao.updateSystemPictur(systemPictur);
		JOptionPane.showMessageDialog(this, "设置成功\n请重新登录");
	}

	/**
	 * 删除
	 */
	private void deletesystemPictur() {
		int yes = JOptionPane.showConfirmDialog(this, "您确认删除该用图片组？", "删除提示",
				JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
		if (yes == JOptionPane.YES_OPTION) {
			SystemPicturSqlDao sDao = new SystemPicturSqlDao();
			SystemPictur s = sDao
					.getSystemPictur("where no=" + txtNo.getText()).get(0);
			String path = s.getPictur1();
			if (path != null) {
				File f = new File(path);
				if (f.exists()) {
					f.delete();// 删除文件
				}

			}
			boolean flag = sDao.deleteSystemPictur(Integer.parseInt(txtNo
					.getText()));
			if (flag) {
				this.dispose();
			} else {
				JOptionPane.showMessageDialog(this, "对不起【删除】失败！");
			}
		}

	}

	/**
	 * 将图片信息显示到窗口的组件上
	 * 
	 * @param systemPictur
	 */
	private void displaysystemPictur(SystemPictur systemPictur) {

		// 显示个人照片
		String path[] = new String[PicturNum];
		path[0] = systemPictur.getPictur1();
		path[1] = systemPictur.getPictur2();
		path[2] = systemPictur.getPictur3();
		path[3] = systemPictur.getPictur4();
		path[4] = systemPictur.getPictur5();
		path[5] = systemPictur.getPictur6();
		path[6] = systemPictur.getPictur7();
		path[7] = systemPictur.getPictur8();
		path[8] = systemPictur.getPictur9();
		path[9] = systemPictur.getPictur10();

		// 系统图片组号
		txtNo.setText(Integer.toString(systemPictur.getNo()));

		// 显示每组各个图片
		for (int i = 0; i < PicturNum; i++) {
			if (path[i] != null) {
				File f = new File(path[i]);
				if (f.exists()) {
					ImageIcon icon = new ImageIcon(path[i]);
					// 图片自适应大小
					icon.setImage(icon.getImage().getScaledInstance(
							lblPicture[i].getWidth(),
							lblPicture[i].getHeight(), Image.SCALE_DEFAULT));
					lblPicture[i].setIcon(icon);
					lblPicture[i].updateUI();
				}
			}
		}

		// 保存到SystemPictur成员变量中
		SystemPictur.setNo(systemPictur.getNo());
		SystemPictur.setPictur1(path[0]);
		SystemPictur.setPictur2(path[1]);
		SystemPictur.setPictur3(path[2]);
		SystemPictur.setPictur4(path[3]);
		SystemPictur.setPictur5(path[4]);
		SystemPictur.setPictur6(path[5]);
		SystemPictur.setPictur7(path[6]);
		SystemPictur.setPictur8(path[7]);
		SystemPictur.setPictur9(path[8]);
		SystemPictur.setPictur10(path[9]);
	}

	/**
	 * 上传图片
	 * 
	 * @param fileName上传图片文件名
	 */
	private void Savepoint(int i, JLabel lblPicture1) {
		// (1)弹出选举文件窗口
		FileDialog fd = new FileDialog(this, "打开文件", FileDialog.LOAD);
		fd.setFile("*.gif");
		fd.setVisible(true);
		// (2)选择文件（图片）
		String dir = fd.getDirectory();// 获取目录
		String fileName = fd.getFile();// 获取文件
		String photoPath;
		String picturPath;
		if (dir != null && fileName != null) {
			// 创建文件对象
			photoPath = dir + "\\" + fileName;
			File f = new File(photoPath);
			if (f.exists()) {
				// 控制文件大小,不超过15KB
				long size = f.length();
				if (size > 5000 * 1024) {
					JOptionPane.showMessageDialog(this, "上传图片不能超过500KB");
					return;
				}
				// 使用文件输入，输出流进行上传图片
				String str = UUID.randomUUID().toString();
				// 获取长传文件的扩展名
				String extension = FilenameUtils.getExtension(photoPath);
				String savePath = "sys_images/";
				// 判断路径是否存在,如果不存在就创建
				File f1 = new File(savePath);
				if (!f1.isDirectory()) {
					f1.mkdirs();
				}
				try {
					FileInputStream fis = new FileInputStream(photoPath);
					FileOutputStream fos = new FileOutputStream(savePath + str
							+ "." + extension);
					byte[] b = new byte[fis.available()];// 获取输入流中可用的字节数
					int length = 0;
					while ((length = fis.read(b)) > 0) {
						fos.write(b, 0, length);
					}
					fis.close();
					fos.close();

				} catch (Exception e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(this, "上传图有误");
					return;
				}
				// 显示长传的图片

				ImageIcon icon = new ImageIcon(savePath + str + "." + extension);
				// 图片自适应大小
				icon.setImage(icon.getImage().getScaledInstance(
						lblPicture1.getWidth(), lblPicture1.getHeight(),
						Image.SCALE_DEFAULT));
				lblPicture1.setIcon(icon);
				lblPicture1.updateUI();
				// 最后根系数据库中图片路径字段内容
				SystemPicturSqlDao sDao = new SystemPicturSqlDao();
				picturPath = savePath + str + "." + extension;
				switch (i) {
				case 0:
					SystemPictur.setPictur1(picturPath);
					break;
				case 1:
					SystemPictur.setPictur2(picturPath);
					break;
				case 2:
					SystemPictur.setPictur3(picturPath);
					break;
				case 3:
					SystemPictur.setPictur4(picturPath);
					break;
				case 4:
					SystemPictur.setPictur5(picturPath);
					break;
				case 5:
					SystemPictur.setPictur6(picturPath);
					break;
				case 6:
					SystemPictur.setPictur7(picturPath);
					break;
				case 7:
					SystemPictur.setPictur8(picturPath);
					break;
				case 8:
					SystemPictur.setPictur9(picturPath);
					break;
				case 9:
					SystemPictur.setPictur10(picturPath);
					break;
				default:
					System.out.println("系统图片输入数据库失败！");

				}
				sDao.updateSystemPictur(SystemPictur);
			}

		}

	}
}
